//
//  KLHomeRefreshControl.swift
//  BCWeiBo
//
//  Created by bcmac3 on 16/4/5.
//  Copyright © 2016年 KellenYangs. All rights reserved.
//

import UIKit

class KLHomeRefreshControl: UIRefreshControl {

    override init()
    {
        super.init()
        // 1.添加子控件
        addSubview(refreshView)
        
        // 2.布局子控件
        refreshView.xmg_AlignInner(type: XMG_AlignType.Center, referView: self, size: CGSize(width: 150, height: 60))
        
        // 3.通过KVO监听自己
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.New, context: nil)
    }
    
    // 显示提示标记
    private var showTipFlag = false
    private var loadingFlag = false
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        /*
        2.1得出结论向下拉, Y值会越小. Y值为负数就会显示
        2.2拉到一定程度会自动刷新
        2.3向上推表格, 刷新控件任然存在没有销毁
        */
        //        print("frame = \(frame)")
        
        // 1.过滤不需要的数据
        if frame.origin.y >= 0
        {
            return
        }
        
        // 判断时候开始加载数据
        if refreshing && !loadingFlag
        {
            refreshView.startLoadingAnim()
            return
        }
        
        if frame.origin.y > -50 && !showTipFlag{
            print("翻过来")
            showTipFlag = true
            refreshView.rotationTipIcon(showTipFlag)
        }else if frame.origin.y <= -50 && showTipFlag
        {
            print("转过去")
            showTipFlag = false
            refreshView.rotationTipIcon(showTipFlag)
        }
    }
    
    override func endRefreshing() {
        super.endRefreshing()
        
        // 停止动画
        refreshView.stopLoadingAnim()
    }
    
    // MARK: - 懒加载
    private lazy var refreshView = HomeRefreshView.refreshView()
    
    deinit
    {
        removeObserver(self, forKeyPath: "frame")
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}


class HomeRefreshView: UIView {
    
    @IBOutlet weak var tipIcon: UIImageView!
    
    @IBOutlet weak var loadingIcon: UIImageView!
    
    @IBOutlet weak var tipView: UIView!
    
    class func refreshView() -> HomeRefreshView {
        return NSBundle.mainBundle().loadNibNamed("HomeRefreshView", owner: nil, options: nil).last as! HomeRefreshView
//        return HomeRefreshView()
    }
    /**
     旋转箭头
     */
    private func rotationTipIcon(showTipFlag: Bool)
    {
        print(showTipFlag)
        var angle = M_PI
        angle += showTipFlag ? -0.01 : 0.01
        UIView.animateWithDuration(0.5) { () -> Void in
            self.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform, CGFloat(angle))
        }
    }
    /**
     开始转圈
     */
    private func startLoadingAnim()
    {
        // 隐藏箭头视图
        tipView.hidden = true;
        // 创建动画
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = 2 * M_PI
        anim.duration = 10.0
        anim.repeatCount = MAXFLOAT
        // 添加动画
        loadingIcon.layer.addAnimation(anim, forKey: nil)
    }
    /**
     停止转圈
     */
    private func stopLoadingAnim()
    {
        // 显示箭头视图
        tipView.hidden = false
        // 移除动画
        loadingIcon.layer.removeAllAnimations()
    }

}
